package com.example.superyi.mainBar;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.databean.Msg;
import com.example.onion.hxchat.activity.InfoActivity;
import com.example.onion.hxchat.activity.MainActivityWC;
import com.example.onion.hxchat.activity.MsgTestActivity;
import com.example.onion.hxchat.fragment.TabViewPagerFragment;
import com.example.onion.hxchat.mvvm.ApplyViewModel;
import com.example.onion.hxchat.mvvm.InfoViewModel;
import com.example.onion.hxchat.mvvm.TeamNotificationViewModel;
import com.example.onion.hxchat.mvvm.WcFriendViewModel;
import com.example.onion.hxchat.room.entity.Apply;
import com.example.onion.hxchat.room.entity.Friend;
import com.example.onion.hxchat.room.entity.Info;
import com.example.onion.hxchat.room.entity.TeamNotification;
import com.example.onion.hxchat.test.TestDefineMessage;
import com.example.onion.hxchat.util.HttpUtils;
import com.example.onion.hxchat.util.MyLocalDatabaseHelper;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.mainBar.fregments.MainFragment_HomePage;
import com.example.superyi.mainBar.fregments.MainFragment_My;
import com.example.superyi.mainBar.fregments.Mianfragment_Team;
import com.example.superyi.myteam.R;
import com.example.superyi.myteam.attentionFragment;
import com.example.superyi.myteam.myAnswer.MyAnswerFragment;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.next.easynavigation.view.EasyNavigationBar;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Request;

public class MainBar extends AppCompatActivity implements EMMessageListener, EMContactListener {

    private String[] tabText = {"首页", "消息", "组队", "我的"};
    //未选中时icon状态
    private int[] normalIcon = {R.mipmap.home, R.mipmap.pic, R.mipmap.team, R.mipmap.user};
    //选中的状态
    private int[] selectIcon = {R.mipmap.home1, R.mipmap.pic1, R.mipmap.team1, R.mipmap.user1};

    private EasyNavigationBar easerBar;
    private List<Fragment> fragments = new ArrayList<Fragment>();
    private Handler mHandler = new Handler();

    private boolean flag = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_bar);

        easerBar = findViewById(R.id.Main_navigationBar);
        fragments.add(new attentionFragment());
        fragments.add(new TabViewPagerFragment());
        fragments.add(new Mianfragment_Team());
        fragments.add(new MainFragment_My());
        easerBar.titleItems(tabText)
                .normalIconItems(normalIcon)
                .selectIconItems(selectIcon)
                .fragmentList(fragments)
                .centerImageRes(R.mipmap.add_image)
                .centerTextStr("发布")
                .centerLayoutRule(EasyNavigationBar.RULE_BOTTOM)
                .centerLayoutBottomMargin(0)
                .centerAlignBottom(true)
                .fragmentManager(getSupportFragmentManager())
                .setOnTabClickListener(new EasyNavigationBar.OnTabClickListener() {
                    @Override
                    public boolean onTabSelectEvent(View view, int position) {
                        return false;
                    }

                    @Override
                    public boolean onTabReSelectEvent(View view, int position) {
                        return false;
                    }

                })
                .setOnCenterTabClickListener(new EasyNavigationBar.OnCenterTabSelectListener() {
                    @Override
                    public boolean onCenterTabSelectEvent(View view) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                //＋ 旋转动画
                                if (flag) {
                                    easerBar.getCenterImage().animate().rotation(45).setDuration(400);
                                } else {
                                    easerBar.getCenterImage().animate().rotation(0).setDuration(400);
                                }
                                flag = !flag;
                            }
                        });
                        return false;
                    }
                })
                .canScroll(true)
                .mode(EasyNavigationBar.NavigationMode.MODE_ADD)
                .build();

        /**
         * WC
         * ****/
        dbHelper = new MyLocalDatabaseHelper(this, "local.db", null, version);
        accountId = PassWordHelp.readPassword(MainBar.this)[0];
        infoViewModel = new ViewModelProvider(this).get(InfoViewModel.class);
        friendViewModel = new ViewModelProvider(this).get(WcFriendViewModel.class);
        applyViewModel = new ViewModelProvider(this).get(ApplyViewModel.class);
        teamNotificationViewModel = new ViewModelProvider(this).get(TeamNotificationViewModel.class);
        infoViewModel.insertInfo(new Info("会出现重复", "last info,用来发信息测试，以后要删", "1234", accountId));

    }


    @Override
    protected void onResume() {
        super.onResume();
        //注册消息监听
        EMClient.getInstance().chatManager().addMessageListener(this);
        //注册好友监听
        EMClient.getInstance().contactManager().setContactListener(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消好友监听
        EMClient.getInstance().contactManager().removeContactListener(this);
    }


    /**
     * 这里用来实现,再点一次返回键退出应用,应该放在首先进入的页面
     *
     * @param keyCode
     * @param event
     * @return
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
//              finish();
//                System.exit(0);
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addCategory(Intent.CATEGORY_HOME);
                startActivity(home);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent home = new Intent(Intent.ACTION_MAIN);
//            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            home.addCategory(Intent.CATEGORY_HOME);
//            startActivity(home);
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    private String accountId;
    private MyLocalDatabaseHelper dbHelper;
    private static final String TAG = "MainActivityWC";
    private int version = 4;
    private static final String FORMATER = "yyyy:MM:dd:HH:mm:ss";
    private InfoViewModel infoViewModel;
    private WcFriendViewModel friendViewModel;
    private ApplyViewModel applyViewModel;
    private TeamNotificationViewModel teamNotificationViewModel;

    /**
     * 生成当前时间                        <br>
     */
    /**
     * 生成当前时间                        <br>
     */
    public static String genCurrentTime() {
        SimpleDateFormat formater = new SimpleDateFormat(FORMATER);
        return formater.format(new Date());
    }

    private String createNotificationChannel(String channelID, String channelNAME, int level) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
            manager.createNotificationChannel(channel);
            return channelID;
        } else {
            return null;
        }
    }

    @Override
    public void onMessageReceived(List<EMMessage> list) {
        Log.e(TAG, "xiaoxi");
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        for (EMMessage message : list) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String messageType = "chatMessage";
                    Log.e("MWC上", messageType);
                    //team操作通知消息类型（邀请入队、删除队伍通知）
                    messageType = message.getStringAttribute(TestDefineMessage.TEAM_NOTIFICATION, "chatMessage");
                    Log.e("MWC", messageType);
                    Log.e("MWC下", messageType);
                    //默认是聊天消息类型
                    if (TestDefineMessage.TEAM_NOTIFICATION_INVITE.equals(messageType)) {
                        Log.e("MWC", "收到队伍消息" + ((EMTextMessageBody) message.getBody()).getMessage());
                        //收到了队伍相关通知的消息(邀请入队)
                        String userId = message.getUserName();//发送邀请入队请求的userId
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                HttpUtils httpUtils = HttpUtils.getInstance();
                                FormBody.Builder builder = new FormBody.Builder();
                                builder.add("userId", userId);
                                FormBody formBody = builder.build();
                                httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/GetUserNameByIdServlet", formBody, new HttpUtils.HttpCallBack() {
                                    @Override
                                    public void onError(Request request, IOException e) {
                                    }

                                    @SuppressLint("LongLogTag")
                                    @Override
                                    public void onSuccess(Request request, String result) {
                                        Gson gson = new Gson();
                                        JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                                        JsonElement jsonElement = resultJson.get("userName");
                                        String userName = jsonElement.getAsString();
                                        TeamNotification teamNotification = new TeamNotification(userId, userName,((EMTextMessageBody) message.getBody()).getMessage(), accountId, TestDefineMessage.TEAM_NOTIFICATION_INVITE);
                                        teamNotificationViewModel.insertTeamNotification(teamNotification);
                                    }
                                });
                            }
                        }).start();

                    } else if (TestDefineMessage.TEAM_NOTIFICATION_DELETE.equals(messageType)) {
                        //收到了队伍相关通知的消息(删除队伍时的提示)
                        String userId = message.getUserName();//发送邀请入队请求的userId
                        TeamNotification teamNotification = new TeamNotification(userId, ((EMTextMessageBody) message.getBody()).getMessage(), accountId, TestDefineMessage.TEAM_NOTIFICATION_DELETE);
                        teamNotificationViewModel.insertTeamNotification(teamNotification);
                    }
                    Intent intent = null;
                    if (messageType.equals("chatMessage")) {
                        intent = new Intent(MainBar.this, MsgTestActivity.class);
                    }
                    assert intent != null;
                    intent.putExtra("chatUserId", message.getUserName());
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivity(MainBar.this, 0, intent, 0);
                    String channelId = createNotificationChannel("my_channel_ID", "my_channel_NAME", NotificationManager.IMPORTANCE_HIGH);
                    Notification.Builder notification;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        notification = new Notification.Builder(MainBar.this, "5996773");
                    } else {
                        notification = new Notification.Builder(MainBar.this);
                    }

                    //NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivityWC.this, channelId)
                    notification
                            //设置标题
                            .setContentTitle(message.getFrom() + "发来一条消息")
                            //设置内容
                            .setContentText(((EMTextMessageBody) message.getBody()).getMessage())
                            //设置状态栏显示的图标，建议图标颜色透明
                            .setSmallIcon(R.mipmap.ic_launcher)
                            // 设置通知灯光（LIGHTS）、铃声（SOUND）、震动（VIBRATE）、（ALL 表示都设置）
                            .setDefaults(Notification.DEFAULT_ALL)
                            //灯光三个参数，颜色（argb）、亮时间（毫秒）、暗时间（毫秒）,灯光与设备有关
                            .setLights(Color.RED, 200, 200)
                            // 铃声,传入铃声的 Uri（可以本地或网上）我这没有铃声就不传了
                            .setSound(Uri.parse(""))
                            // 震动，传入一个 long 型数组，表示 停、震、停、震 ... （毫秒）
                            .setVibrate(new long[]{0, 200, 200, 200, 200, 200})
                            // 通知栏点击后自动消失
                            .setAutoCancel(true)
                            // 简单通知栏设置 Intent
                            .setContentIntent(pendingIntent)
                            .setPriority(Notification.PRIORITY_HIGH);
//                            .setContentTitle(message.getFrom())
//                            .setContentText("收到一条消息")
//                            .setWhen(System.currentTimeMillis())//通知栏显示时间
//                            .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
//                            .setSmallIcon(R.mipmap.ic_launcher)//通知栏小图标
//                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//通知栏下拉是图标
//                            .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
//                            .setPriority(NotificationCompat.PRIORITY_MAX)//设置通知消息优先级
//                            .setAutoCancel(true)//设置点击通知栏消息后，通知消息自动消失
//                            .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.message_arrive))
//                            .setVibrate(new long[]{0, 1000, 1000, 1000})
////                .setSound(Uri.fromFile(new File("/system/MP3/music.mp3"))) //通知栏消息提示音
////                            .setVibrate(new long[]{0, 1000, 1000, 1000}) //通知栏消息震动
////                            .setLights(Color.GREEN, 1000, 2000) //通知栏消息闪灯(亮一秒间隔两秒再亮)
////                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) //通知栏提示音、震动、闪灯等都设置为默认
//                            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
////                            .setStyle(new NotificationCompat.InboxStyle()
////                                    .addLine(((EMTextMessageBody) message.getBody()).getMessage()))
//                            .setAutoCancel(true)
//                            .setStyle(new Notification().BigTextStyle().
//                                    bigText(((EMTextMessageBody) message.getBody()).getMessage()));

                    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainBar.this);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        NotificationChannel channel = new NotificationChannel("5996773", "安卓10a", NotificationManager.IMPORTANCE_DEFAULT);
                        channel.enableLights(true);//是否在桌面icon右上角展示小红点
                        channel.setLightColor(Color.GREEN);//小红点颜色
                        channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
                        notificationManager.createNotificationChannel(channel);
                    }
                    notificationManager.notify(100, notification.build());
                    Msg msg = new Msg(((EMTextMessageBody) message.getBody()).getMessage(), Msg.TYPE_RECEIVED, message.getUserName(), accountId, genCurrentTime());
//                    Message message1 = new Message(message.getUserName(),((EMTextMessageBody) message.getBody()).getMessage(),accountId,Msg.TYPE_RECEIVED,genCurrentTime());
//                    messageViewModel.insertMessage(message1);
                    db.execSQL("insert into chatDb(userId,toUserId,content,type,time) values(?,?,?,?,?)"
                            , new String[]{msg.getUserId(), msg.getToUserId(), msg.getContent(), String.valueOf(msg.getType()), msg.getTime()});
                    Log.e("MainWc", "存储一条消息" + ((EMTextMessageBody) message.getBody()).getMessage());
                    if (!isExistUserIdInfo(message.getUserName())) {
                        //不存在与userId用户的对话框插入
                        Info info = new Info(message.getUserName(), ((EMTextMessageBody) message.getBody()).getMessage(), message.getUserName(), accountId, 1);
                        Log.e("MainWc", "创建新的对话窗口");
                        infoViewModel.insertInfo(info);
                        //以下是没有使用ViewModel的对话框，现在只是用来作为一个判断本地是否已经有此对话框使用，跟着ViewModel的对话框一起存本地sqlite(但是是不同的数据库）
                        db.execSQL("insert into infoItem(userId,userName,lastInfo,ownerUserId) values(?,?,?,?)"
                                , new String[]{message.getUserName(), message.getUserName(), ((EMTextMessageBody) message.getBody()).getMessage(), accountId});
                    } else {//存在只需修改最新一条消息即可
                        infoViewModel.lastInfoAndInfoNum(((EMTextMessageBody) message.getBody()).getMessage(), message.getUserName(), accountId);
                        Log.e("MainWc", "原有窗口基础上修改信息");
                        //                        db.execSQL("update infoItem set lastInfo = ? where userId = ? and ownerUserId =?"
//                                , new String[]{((EMTextMessageBody) message.getBody()).getMessage(), message.getUserName(),accountId});
                    }
                    Log.e("消息的用户名", message.getUserName());
                }
        });
    }
    //此处可以写保存聊天信息到本地数据库
    //环信导入消息到数据库（对于消息，环信sdk会自动创建本地数据库) 但是没用到
        EMClient.getInstance().chatManager().importMessages(list);
}

    /**
     * 判断数据库是否存在与userId用户的对话框
     *
     * @param userId id
     * @return 存在true 否则false
     */
    private boolean isExistUserIdInfo(String userId) {
//        return infoViewModel.isExistInfo(userId,accountId);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select userName from infoItem where userId = ? and ownerUserId=?"
                , new String[]{userId, accountId});
        if (cursor.moveToFirst()) {//查出来数据表示存在与userId用户的对话框了
            return true;
        }
        return false;
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageRead(List<EMMessage> list) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {

    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }


    @Override
    public void onContactAdded(String s) {
        //增加联系人时回调此方法
    }

    @Override
    public void onContactDeleted(String s) {
        //被删除时回调此方法
    }

    @Override
    public void onContactInvited(String s, String s1) {
        //收到好友邀请 s 用户id  s1 reason
        Intent intent = new Intent(MainBar.this, InfoActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(MainBar.this, 0, intent, 0);
        String channelId = createNotificationChannel("my_channel_ID", "my_channel_NAME", NotificationManager.IMPORTANCE_HIGH);
        assert channelId != null;
        NotificationCompat.Builder notification = new NotificationCompat.Builder(MainBar.this, channelId)
                .setContentTitle(s + ":申请添加好友，快来看看吧！")
                //.setContentText("好友申请，快来看看吧！")
                .setWhen(System.currentTimeMillis())//通知栏显示时间
                .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
                .setSmallIcon(R.mipmap.ic_launcher)//通知栏小图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//通知栏下拉是图标
                .setContentIntent(pendingIntent)//关联点击通知栏跳转页面
                .setPriority(NotificationCompat.PRIORITY_MAX)//设置通知消息优先级
                .setAutoCancel(true)//设置点击通知栏消息后，通知消息自动消失
//                .setSound(Uri.fromFile(new File("/system/MP3/music.mp3"))) //通知栏消息提示音
                .setVibrate(new long[]{0, 1000, 1000, 1000}) //通知栏消息震动
                .setLights(Color.GREEN, 1000, 2000) //通知栏消息闪灯(亮一秒间隔两秒再亮)
                .setDefaults(NotificationCompat.DEFAULT_ALL) //通知栏提示音、震动、闪灯等都设置为默认
                .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setStyle(new NotificationCompat.InboxStyle().addLine(s1))
                .setAutoCancel(true);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainBar.this);
        notificationManager.notify(100, notification.build());

//        Apply apply = new Apply();

        SQLiteDatabase db = dbHelper.getWritableDatabase();

        HttpUtils httpUtils = HttpUtils.getInstance();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("userId", s);
        FormBody formBody = builder.build();
        httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/GetUserNameByIdServlet", formBody, new HttpUtils.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {

            }

            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(Request request, String result) {
                Gson gson = new Gson();
//                        JsonObject resultJson = gson.fromJson(result, JsonObject.class);
//                        JsonElement jsonElement = resultJson.get("state");
//                        Log.e("login Result ",resultJson.toString());
//                        if (jsonElement.getAsString().equals("success"))
                JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                JsonElement jsonElement = resultJson.get("userName");
                String userName = jsonElement.getAsString();
                db.execSQL("insert into notification(userId,userName,applyContent) values(?,?,?)"
                        , new String[]{s, userName, s1});

                Apply apply = new Apply(userName, s, s1, accountId);
                applyViewModel.insertApply(apply);
                Log.e("MainActivityWc", "根源获取好友昵称！.");
                Log.e("MainActivityWcName", userName);
            }
        });

    }

    @Override
    public void onFriendRequestAccepted(String s) {
        //好友请求被同意
        HttpUtils httpUtils = HttpUtils.getInstance();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("userId", s);
        FormBody formBody = builder.build();
        httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/GetUserNameByIdServlet", formBody, new HttpUtils.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {

            }

            @Override
            public void onSuccess(Request request, String result) {
                Gson gson = new Gson();
                JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                JsonElement jsonElement = resultJson.get("userName");
                String userName = jsonElement.getAsString();
                Friend friend = new Friend(userName, s, accountId);
                friendViewModel.insertFriend(friend);
                Log.e("MainWc", "本地保存好友信息成功.");
            }
        });


//        Friend friend = new Friend(s,s,accountId);
//        friendViewModel.insertFriend(friend);
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        db.execSQL("insert into friend(userId,userName) values(?,?)",new String[]{s,s});
    }

    @Override
    public void onFriendRequestDeclined(String s) {
        //好友请求被拒绝
    }

}
